#include "gd32w51x.h"
#include "stdio.h"
#include "math.h"
#include "DevicesIIS.h"


int16_t g_usIISPalyDatas[PLAY_BUFFER_SIZE] = {0};


void vIIS1Init(void)
{
    /* cofigure I2S clock */
    rcu_hxtal_plli2s_enable();
    rcu_plli2s_config(48, RCU_PLLI2SSRC_DIV8, RCU_PLLI2S_DIV6);
    rcu_osci_on(RCU_PLLI2S_CK);
    while(0 == (RCU_CTL & RCU_CTL_PLLI2SSTB));
    rcu_i2s_clock_config(RCU_I2SSRC_PLLI2S);

    /* enable GPIO clock */
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_GPIOB);
    /* enable I2S1 clock */
    rcu_periph_clock_enable(RCU_SPI1);



    /* I2S1_MCK(PA5), I2S1_CK(PB8), I2S1_WS(PA7), I2S1_SD(PA4) GPIO pin configuration */
    gpio_af_set(GPIOA, GPIO_AF_6, GPIO_PIN_4);
    gpio_af_set(GPIOA, GPIO_AF_2, GPIO_PIN_5);
    gpio_af_set(GPIOB, GPIO_AF_5, GPIO_PIN_8);
    gpio_af_set(GPIOA, GPIO_AF_0, GPIO_PIN_7);
    gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_7);
    gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_8);
    gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_166MHZ, GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_7);
    gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_166MHZ, GPIO_PIN_8);



    /* I2S1 peripheral configuration */
    i2s_psc_config(SPI1, I2S_AUDIOSAMPLE_8K, I2S_FRAMEFORMAT_DT16B_CH16B, I2S_MCKOUT_ENABLE);
    i2s_init(SPI1, I2S_MODE_MASTERTX, I2S_STD_MSB, I2S_CKPL_HIGH);

    /* enable interrupt */
    nvic_irq_enable(SPI1_IRQn, 2, 0);

    spi_i2s_interrupt_enable(SPI1, SPI_I2S_INT_TBE);


    /* enable the I2S1 peripheral */
    i2s_enable(SPI1);


    cIISSetSineWave(20000.0f, 0.0f);
}

#define IIS_PI 3.1415927f
/* 采样频率 */
#define IIS_SAMPLE_FREQUENCY 8000.0f

int8_t cIISSetSineWave(float fFrequency, float fPhase)
{
    int32_t i = 0;

    for(i = 0; i < PLAY_BUFFER_SIZE / 2; ++i)
    {
        g_usIISPalyDatas[i * 2] =     4096.0f * cos(2.0f * IIS_PI * i / IIS_SAMPLE_FREQUENCY * fFrequency - fPhase / 180.0f * IIS_PI);
        g_usIISPalyDatas[i * 2 + 1] = 4096.0f * cos(2.0f * IIS_PI * i / IIS_SAMPLE_FREQUENCY * fFrequency - fPhase / 180.0f * IIS_PI);
    }

    return 0;
}

